package com.tgy.files.service.impl;

import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.tgy.files.resource.FileResource;
import com.tgy.files.service.FileService;
import com.tgy.util.aliyun.AliyunResource;
import org.n3r.idworker.Sid;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;

@Service
public class FileServiceImpl implements FileService {

    @Resource
    private FileResource fileResource;
    @Resource
    private AliyunResource aliyunResource;
    @Resource
    private Sid sid;

    @Override
    public String uploadOSS(MultipartFile file, String userId,String type, String fileExtName) throws Exception {
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = fileResource.getEndpoint();
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。
        // 强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = aliyunResource.getAccessKeyId();
        String accessKeySecret = aliyunResource.getAccessKeySecret();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint,
                accessKeyId,
                accessKeySecret);
//        images/abc/10010/dog.png

        String fileName = sid.nextShort();

        if (StrUtil.isBlank(userId)){
            userId = "tgyBlog";
        }

        //路劲(默认头像路劲)
        String myObjectName = fileResource.getAvatarName()
                + "/" + userId + "/" + fileName + "." + fileExtName;;

        if ("avatar".equals(type)){
            myObjectName = fileResource.getAvatarName()
                    + "/" + userId + "/" + fileName + "." + fileExtName;
        }else if ("article".equals(type)){
            myObjectName = fileResource.getArticleName()
                    + "/" + userId + "/" + fileName + "." + fileExtName;
        }

        // 上传网络流。
        InputStream inputStream = file.getInputStream();
        ossClient.putObject(fileResource.getBucketName(),
                myObjectName,
                inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();

        return myObjectName;
    }
}
